import { ref } from 'vue'
import { defineStore } from 'pinia'

const USER_INFO_KEY = 'yt_manager_user_info'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref({})

  // 初始化时从localStorage恢复用户信息
  function initUserInfo() {
    try {
      const storedUserInfo = localStorage.getItem(USER_INFO_KEY)
      if (storedUserInfo) {
        userInfo.value = JSON.parse(storedUserInfo)
      }
    } catch (error) {
      console.error('Failed to parse user info from localStorage:', error)
      localStorage.removeItem(USER_INFO_KEY)
    }
  }

  // 设置用户信息
  function setUserInfo(info) {
    userInfo.value = info
    // 保存到localStorage实现持久化
    try {
      localStorage.setItem(USER_INFO_KEY, JSON.stringify(info))
    } catch (error) {
      console.error('Failed to save user info to localStorage:', error)
    }
  }

  // 清除用户信息
  function clearUserInfo() {
    userInfo.value = {}
    // 同时清除localStorage中的用户信息
    localStorage.removeItem(USER_INFO_KEY)
  }

  // 检查用户是否已登录
  function isLoggedIn() {
    return !!userInfo.value?.userInfoVO?.token
  }

  return { 
    userInfo, 
    initUserInfo,
    setUserInfo, 
    clearUserInfo,
    isLoggedIn
  }
})